﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using WebSocketService.Tools;

namespace WebSocketService
{
    public partial class WebSocketService : ServiceBase
    {
        string filePath = @"C:\WebSocketServiceLog.txt";

        public WebSocketService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            using (FileStream stream = new FileStream(filePath, FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                MyTimer();
                writer.WriteLine($"{DateTime.Now},服务启动！");
            }
        }

        protected override void OnStop()
        {
            using (FileStream stream = new FileStream(filePath, FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now},服务停止！");
            }
        }

        //实例化System.Timers.Timer   
        private void MyTimer()
        {
            System.Timers.Timer MT = new System.Timers.Timer(10000);
            MT.Elapsed += new System.Timers.ElapsedEventHandler(MTimedEvent);
            MT.Enabled = true;
            //MT.AutoReset = false;//只执行一次

        }

        //构造System.Timers.Timer实例   间隔时间事件   
        private void MTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            SendMainData();
        }

        /// <summary>
        /// 推送主页面数据
        /// </summary>
        private void SendMainData()
        {
            var ws = WebSocketHelper.GetInstance();
            ws.SendMsg(new MessageModel
            {
                MessageContent = $"测试时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss}",
                ModelCode = "ModelCode",
                Token = string.Empty,
                Type = 1,
                UserIdList = new List<string>()
            });
        }

        /// <summary>
        /// 写入到文件
        /// </summary>
        private void WriteFile(string str)
        {
            using (FileStream stream = new FileStream(filePath, FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine(str);
            }
        }
    }
}
